package cn.hesion.thread.futureandpromise;
/**
 * ClassName: GuavaFutureDemo <br/>
 * Description: <br/>
 * date: 2022/4/30 14:30<br/>
 *
 * @author Hesion<br />
 * @version
 * @since JDK 1.8
 */

import com.google.common.util.concurrent.*;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

/**
 *
 * @author: hesion
 * @create: 2022-04-30 14:30
 **/
public class GuavaFutureDemo {

    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
        ListenableFuture<Integer> guavaFuture = service.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("执行耗时操作.....");
                timeConsumingOperation();
                return 100;
            }
        });
        Futures.addCallback(guavaFuture, new FutureCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                System.out.println("计算结果:"+integer);
            }

            @Override
            public void onFailure(Throwable throwable) {
                System.out.println("异步处理失败:"+throwable);
            }
        });
        System.out.println("主线程运行耗时:"+(System.currentTimeMillis()-l));
    }

    private static void timeConsumingOperation() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
